package com.donger.auth.endpoint;


import cn.hutool.core.util.StrUtil;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 退出切入点
 *
 * @author xyx
 */
@RestController
@RequestMapping("/token")
@AllArgsConstructor
public class BootTokenEndpoint {

    private final TokenStore tokenStore;

    private final ClientDetailsService clientDetailsService;


    /**
     * 退出token
     *
     * @param authHeader Authorization
     */
    @DeleteMapping("/logout")
    public Result logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {

        String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);


        if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
            return Res.error("退出失败，token 无效");
        }

        OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
        tokenStore.removeAccessToken(accessToken);
        return Res.ok("退出登陆");
    }


}